//
//  PhotoSelectorCell.swift
//  照片选择器
//
//  Created by rong on 15/7/12.
//  Copyright © 2015年 rong. All rights reserved.
//

import UIKit
import FFAutoLayout

@objc
protocol PhotoSelectorCellDelegate: NSObjectProtocol {
    
    optional func PhotoSelectorCellSelectPhoto()
    optional func PhotoSelectorCellDeletePhoto(cell: PhotoSelectorCell)
}

class PhotoSelectorCell: UICollectionViewCell {
    
    var image: UIImage? {
        didSet {
            
            if image == nil{
                photoBtn.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
                photoBtn.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
            } else {
                photoBtn.setImage(image, forState: UIControlState.Normal)
            }
            
            deleteBtn.hidden = (image == nil)
        }
    }
    
    //代理
    weak var SelectPhotoDelegate: PhotoSelectorCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareForUI()
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func selectPhoto() {
        
        if image == nil {
            //前面如果是nil, 后面是！也不会有事
            SelectPhotoDelegate?.PhotoSelectorCellSelectPhoto!()
        }
    }
    
    func deletePhoto() {
        SelectPhotoDelegate?.PhotoSelectorCellDeletePhoto!(self)
    }
    
    private func prepareForUI() {
        
        //注意 photoBtn 和 deleteBtn 的层次关系， deleteBtn 在上层
        addSubview(photoBtn)
        addSubview(deleteBtn)
        
        deleteBtn.hidden = true
        
        photoBtn.ff_Fill(self)
        deleteBtn.ff_AlignInner(ff_AlignType.TopRight, referView: self, size: nil)
        
        photoBtn.addTarget(self, action: "selectPhoto", forControlEvents: UIControlEvents.TouchUpInside)
        photoBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFill//.ScaleAspectFit
        
        deleteBtn.addTarget(self, action: "deletePhoto", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    //“分类” 还可以通过 “类函数” 来实现
    private class func newButton(imageName: String) -> UIButton {
        
        let btn = UIButton()
        
        btn.setImage(UIImage(named: imageName), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: imageName+"_highlighted"), forState: UIControlState.Highlighted)
        
        return btn
    }
    
    //懒加载
    private lazy var deleteBtn: UIButton = PhotoSelectorCell.newButton("compose_photo_close")
    private lazy var photoBtn: UIButton = PhotoSelectorCell.newButton("compose_pic_add")
}
